import 'package:dio/dio.dart';
import 'package:my_blog_flutter/app/config/app_environment.dart';
import 'interceptor/header_interceptor.dart';
import 'interceptor/response_handler_interceptor.dart';

class HttpsClient {
  static String domain = AppEnvironment.instance.baseUrl;
  static Dio? _dio;

  static Dio get dio {
    if (_dio == null) {
      _dio = Dio();
      _dio!.options.baseUrl = domain;
      _dio!.options.connectTimeout = const Duration(milliseconds: 10000); //10s
      _dio!.options.receiveTimeout = const Duration(milliseconds: 10000);

      // 添加拦截器
      _dio!.interceptors.add(HeaderInterceptor());
      _dio!.interceptors.add(ResponseHandlerInterceptor());

      // 添加日志拦截器（开发环境）
      _dio!.interceptors.add(LogInterceptor(
        requestBody: true,
        responseBody: true,
        requestHeader: true,
        responseHeader: true,
        error: true,
      ));
    }
    return _dio!;
  }

  HttpsClient() {
    // 确保dio已初始化
    dio;
  }

  Future get(apiUrl) async {
    try {
      print("HttpsClient GET请求: ${dio.options.baseUrl}$apiUrl");
      var response = await dio.get(apiUrl);
      print("HttpsClient GET响应: ${response.statusCode}");
      return response;
    } catch (e) {
      if (e is DioException) {
        print("HttpsClient GET请求失败: ${e.type} - ${e.message}");
        print("请求URL: ${e.requestOptions.uri}");
        if (e.response != null) {
          print("响应状态码: ${e.response!.statusCode}");
          print("响应数据: ${e.response!.data}");
        }
      } else {
        print("HttpsClient GET未知错误: $e");
      }
      return null;
    }
  }

  Future post(String apiUrl, {Map? data}) async {
    try {
      print("HttpsClient POST请求: ${dio.options.baseUrl}$apiUrl");
      var response = await dio.post(apiUrl, data: data);
      print("HttpsClient POST响应: ${response.statusCode}");
      return response;
    } catch (e) {
      if (e is DioException) {
        print("HttpsClient POST请求失败: ${e.type} - ${e.message}");
        print("请求URL: ${e.requestOptions.uri}");
        if (e.response != null) {
          print("响应状态码: ${e.response!.statusCode}");
          print("响应数据: ${e.response!.data}");
        }
      } else {
        print("HttpsClient POST未知错误: $e");
      }
      return null;
    }
  }

  static replaeUri(picUrl) {
    String tempUrl = domain + picUrl;
    return tempUrl.replaceAll("\\", "/");
  }
}
